package com.jielihaofeng.subscriptions.util;

import com.alibaba.fastjson.JSON;

import javax.xml.bind.DatatypeConverter;
import java.security.MessageDigest;
import java.util.Arrays;
import java.util.TreeMap;

/**
 * @description 请求去重工具类
 * @author Johnnie Wind
 * @date 2020/12/8 23:41
 */
public class RequestDuplicateHelper {

    /**
     * @description 剔除请求的参数并进行MD5摘要
     * @author Johnnie Wind
     * @date 2020/12/8 23:56
     * @Param [reqJson, excludeKeys]
     * @return java.lang.String
     */
    public static String reqParamMD5(final String reqJson, String... excludeKeys){
        String decreptParam = reqJson;

        TreeMap paramTreeMap = JSON.parseObject(decreptParam, TreeMap.class);
        if (excludeKeys!=null) {
            Arrays.asList(excludeKeys).stream().forEach(excludeKey -> paramTreeMap.remove(excludeKey));
        }

        String paramTreeMapJSON = JSON.toJSONString(paramTreeMap);
        String md5DecreptParam = jdkMD5(paramTreeMapJSON);

        return md5DecreptParam;
    }

    /**
     * @description jdK MD5摘要算法
     * @author Johnnie Wind
     * @date 2020/12/8 23:56
     * @Param [src]
     * @return java.lang.String
     */
    private static String jdkMD5(String src){
        String res =null;
        try {
            MessageDigest messageDigest = MessageDigest.getInstance("MD5");
            byte[] resBytes = messageDigest.digest(src.getBytes());
            res = DatatypeConverter.printHexBinary(resBytes);
        }catch (Exception e){
            e.printStackTrace();
        }
        return res;
    }

}
